package com.hjq.mallcoupon.service.impl;

import com.hjq.mallcoupon.entity.SeckillSkuRelationEntity;
import com.hjq.mallcoupon.service.SeckillSkuRelationService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hjq.common.utils.PageUtils;
import com.hjq.common.utils.Query;

import com.hjq.mallcoupon.dao.SeckillSessionDao;
import com.hjq.mallcoupon.entity.SeckillSessionEntity;
import com.hjq.mallcoupon.service.SeckillSessionService;


@Service("seckillSessionService")
public class SeckillSessionServiceImpl extends ServiceImpl<SeckillSessionDao, SeckillSessionEntity> implements SeckillSessionService {
    @Autowired
    SeckillSkuRelationService relationService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<SeckillSessionEntity> queryWrapper = new QueryWrapper<>();


        IPage<SeckillSessionEntity> page = this.page(
                new Query<SeckillSessionEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<SeckillSessionEntity> upLoadSeckillIn3Days() {
        //计算最近时间
        String startTime = getStartTime(0);
        String endTime = getEndTime(2);
        List<SeckillSessionEntity> sessionEntities = baseMapper.upLoadSeckillIn3Days(startTime, endTime);
        if(sessionEntities!=null && sessionEntities.size()!=0){
            sessionEntities.forEach(sessionEntity -> {
                List<SeckillSkuRelationEntity> relationEntities = relationService.list(new QueryWrapper<SeckillSkuRelationEntity>().eq("promotion_session_id", sessionEntity.getId()));
                sessionEntity.setRelationEntities(relationEntities);
            });
        }
        return sessionEntities;
    }
    private String getStartTime (Integer days){
        LocalDate localDate=LocalDate.now();
        LocalDate beginDate = localDate.plusDays(days);
        LocalTime min=LocalTime.MIN;
        return LocalDateTime.of(beginDate,min).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

    }
    private String getEndTime (Integer days){
        LocalDate localDate=LocalDate.now();
        LocalDate endDate = localDate.plusDays(days);
        LocalTime max=LocalTime.MAX;
        return LocalDateTime.of(endDate,max).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) ;

    }

}